package com.xuxin.baby.activity;

import android.content.Intent;
import android.os.Handler;
import android.os.Message;
import android.view.KeyEvent;
import android.view.View;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;

import com.blankj.utilcode.util.ActivityUtils;
import com.blankj.utilcode.util.AppUtils;
import com.blankj.utilcode.util.LogUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.liulishuo.okdownload.DownloadTask;
import com.liulishuo.okdownload.SpeedCalculator;
import com.liulishuo.okdownload.core.breakpoint.BreakpointInfo;
import com.liulishuo.okdownload.core.cause.EndCause;
import com.liulishuo.okdownload.core.listener.assist.Listener4SpeedAssistExtend;
import com.lxj.xpopup.XPopup;
import com.xuxin.baby.R;
import com.xuxin.baby.base.BaseConstant;
import com.xuxin.baby.bean.UpdateBean;
import com.xuxin.baby.contract.HomeContract;
import com.xuxin.baby.event.BaseEventActivity;
import com.xuxin.baby.event.MainActivityEvent;
import com.xuxin.baby.listener.OnUpdateDownloadListener;
import com.xuxin.baby.page.HealthFragment;
import com.xuxin.baby.page.MainFragment;
import com.xuxin.baby.page.TeachFragment;
import com.xuxin.baby.page.UserFragment;
import com.xuxin.baby.popup.UpdatePopup;
import com.xuxin.baby.presenter.HomePresenter;
import com.xuxin.baby.utils.ACache;
import com.xuxin.baby.utils.PathUtils;
import com.xuxin.smartTabLayout.CommonTabLayout;
import com.xuxin.smartTabLayout.listener.CustomTabEntity;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.io.File;
import java.util.ArrayList;

import butterknife.BindView;

/**
 * Created by xu_xin
 * Created on 2020.08.11 0011
 * 主页main
 */
public class MainActivity extends BaseEventActivity implements HomeContract.View {
    private final HomeContract.Presenter presenter = new HomePresenter(this);
    private final ArrayList<CustomTabEntity> mEntity = new ArrayList<>();
    private final ArrayList<Fragment> mFragments = new ArrayList<>();
    @BindView(R.id.main_tab)
    CommonTabLayout main_tab;
    private String tenantId;//租户id
    private String token;//授权token

    @Override
    public void setContentView() {
        setContentView(R.layout.activity_main);
    }

    @Override
    public void initView() {
        mEntity.add(new MainEntity("首页", R.mipmap.img_home_on, R.mipmap.img_home));
        mEntity.add(new MainEntity("精婴早教", R.mipmap.img_teach_on, R.mipmap.img_teach));
        mEntity.add(new MainEntity("儿童保健", R.mipmap.img_health_on, R.mipmap.img_health));
        mEntity.add(new MainEntity("个人中心", R.mipmap.img_me_on, R.mipmap.img_me));
        mFragments.add(MainFragment.newInstance());
        mFragments.add(TeachFragment.newInstance());
        mFragments.add(HealthFragment.newInstance());
        mFragments.add(UserFragment.newInstance());
        main_tab.setTabData(mEntity, this, R.id.main_frame, mFragments);
        main_tab.setCurrentTab(0);
    }

    @Override
    public void initData() {
        ACache aCache = ACache.get(this);
        tenantId = aCache.getAsString(BaseConstant.tenantId);
        token = aCache.getAsString(BaseConstant.token);
        handler.sendEmptyMessageDelayed(0, 5000);
    }

    @Override
    public void onComplete() {

    }

    @Override
    public void onClick(View view) {

    }

    private final Handler handler = new Handler(new Handler.Callback() {
        @Override
        public boolean handleMessage(@NonNull Message msg) {
            if (msg.what == 0) {
                presenter.getUpdate(tenantId, token);
            }
            return false;
        }
    });

    private UpdatePopup updatePopup;

    @Override
    public void onSuccess(UpdateBean updateBean) {
        if (null != updateBean && null != updateBean.getResult()) {
            try {
                int version = Integer.parseInt(updateBean.getResult().getAppVersion());
                if (version > AppUtils.getAppVersionCode()) {
                    new XPopup.Builder(context)
                            .dismissOnTouchOutside(false)
                            .dismissOnBackPressed(false)
                            .asCustom(updatePopup = new UpdatePopup(context, new UpdatePopup.OnUpdateConfirmListener() {
                                @Override
                                public void OnUpdateConfirm() {
                                    download(updateBean);
                                }
                            }))
                            .show();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    private DownloadTask task;

    private void download(UpdateBean updateBean) {
        try {
            task = new DownloadTask.Builder(updateBean.getResult().getUpdateUrl(),
                    new File(PathUtils.getPath() + "/update"))
                    .setFilename("update.apk")
                    .setMinIntervalMillisCallbackProcess(100)
                    .setPassIfAlreadyCompleted(false)
                    .setPriority(10)
                    .build();
            task.enqueue(new OnUpdateDownloadListener() {
                @Override
                public void infoReady(@NonNull DownloadTask task, @NonNull BreakpointInfo info, boolean fromBreakpoint,
                                      @NonNull Listener4SpeedAssistExtend.Listener4SpeedModel model) {
                    if (null != updatePopup) {
                        if (null != task.getInfo()) {
                            long totalLength = task.getInfo().getTotalLength();
                            updatePopup.setProgressMax(totalLength);
                        }
                    }
                }

                @Override
                public void progress(@NonNull DownloadTask task, long currentOffset, @NonNull SpeedCalculator taskSpeed) {
                    if (null != updatePopup) {
                        if (null != task.getInfo()) {
                            long totalOffset = task.getInfo().getTotalOffset();
                            updatePopup.updateProgress("速度：" + taskSpeed.speed(), totalOffset);
                        }
                    }
                }

                @Override
                public void taskEnd(@NonNull DownloadTask task, @NonNull EndCause cause, @Nullable Exception realCause,
                                    @NonNull SpeedCalculator taskSpeed) {
                    if (cause == EndCause.COMPLETED) {
                        AppUtils.installApp(task.getFile());
                        LogUtils.e("任务完成");
                    } else if (cause == EndCause.CANCELED) {
                        LogUtils.e("任务取消");
                    } else if (cause == EndCause.ERROR) {
                        LogUtils.e("下载失败");
                        ToastUtils.showShort("下载失败");
                    } else {
                        LogUtils.e("cause = " + cause.name());
                    }
                    if (null != updatePopup) {
                        updatePopup.dismiss();
                    }
                }
            });
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private long exitTime = 0;

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK && event.getAction() == KeyEvent.ACTION_DOWN) {
            if ((System.currentTimeMillis() - exitTime) > 2000) {
                ToastUtils.showShort("再按一次退出");
                exitTime = System.currentTimeMillis();
            } else {
                ActivityUtils.finishAllActivities();
            }
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    public static class MainEntity implements CustomTabEntity {
        private final String title;
        private final int selected_id;
        private final int unselected_id;

        private MainEntity(String title, int selected, int unselected) {
            this.title = title;
            this.selected_id = selected;
            this.unselected_id = unselected;
        }

        @Override
        public String getTabTitle() {
            return title;
        }

        @Override
        public int getTabSelectedIcon() {
            return selected_id;
        }

        @Override
        public int getTabUnselectedIcon() {
            return unselected_id;
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(MainActivityEvent event) {
        main_tab.setCurrentTab(1);
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        LogUtils.e("onNewIntent");
    }

    @Override
    protected void onDestroy() {
        if (null != task) {
            task.cancel();
        }
        super.onDestroy();
    }
}